<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPrem('addEmployee')" size="small" type="primary" @click="dialogShow">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" sortable="" width="110">
            <template #default="obj">
              <img
                v-fixImg="require('@/assets/common/bigUserHeader.png')"
                :src="obj.row.staffPhoto"
                alt=""
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="showCode(obj.row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatterFn" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="obj">
              {{ obj.row.timeOfEntry|formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="obj">
              <el-switch
                v-model="obj.row.enableState"
                :active-value="1"
                :inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="250px">
            <template #default="obj">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${obj.row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleDialogFn(obj.row.id)">角色</el-button>
              <el-button v-if="checkPrem('delEmployee')" type="text" size="small" @click="delEmployee(obj.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="pageConfig.size" :total="total" @current-change="currentChange" />
        </el-row>
      </el-card>
    </div>
    <addDialog :show-dialog.sync="showDialog" @addSuccess="getEmpList()" />
    <el-dialog title="二维码" :visible="isShowCode" @close="isShowCode=false">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <role-dialog ref="roleDialog" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employee'
import EnumEmployee from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import addDialog from './components/addDialog.vue'
import RoleDialog from './components/roleDialog.vue'
import QRCode from 'qrcode'
export default {
  components: { addDialog, RoleDialog },
  data() {
    return {
      employeeList: [],
      total: 0,
      pageConfig: {
        page: 1,
        size: 5
      },
      showDialog: false,
      showRoleDialog: false,
      userId: '',
      isShowCode: false
    }
  },
  async created() {
    this.getEmpList()
  },
  methods: {
    // 获取员工列表
    async getEmpList() {
      const res = await getEmployeeList(this.pageConfig)
      // console.log(51, res)
      this.employeeList = res.rows.map(user => {
        const state = Math.round(Math.random())
        return { ...user, enableState: user.enableState || state }
      })
      this.total = res.total
    },
    // 换页
    currentChange(val) {
      this.pageConfig.page = val
      this.getEmpList()
    },
    // 加工聘用形式数据，formatter为插件自带的参数
    formatterFn(row, col, cellVal) {
      // console.log(row, col, cellVal)
      const obj = EnumEmployee.hireType.find(item => Number(item.id) === Number(cellVal))
      return obj ? obj.value : ''
    },
    // 删除按钮
    async delEmployee(id) {
      await this.$confirm('确定要删除？')
      await delEmployee(id)
      this.$message.success('删除成功')
      // 当删除时当页已经没有数据，自动跳转到上一页
      if (this.employeeList.length === 1 && this.pageConfig.page > 1) {
        this.pageConfig.page--
      }
      this.getEmpList()
    },
    // 导出功能
    async exportExcel() {
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      // console.log(101, rows)
      const data = rows.map(item => {
        return this.objToArr(item)
      })
      const header = ['姓名', '手机号', '工号', '聘用形式', '入职时间']
      export_json_to_excel({
        header,
        data
      })
    },
    // 把对象转为数组
    objToArr(userobj) {
      // console.log(userobj)
      const userArr = []
      const zidian = {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职时间': 'timeOfEntry'
      }
      for (const key in zidian) {
        const enkey = zidian[key]
        const value = userobj[enkey]
        if (enkey === 'formOfEmployment') {
          const obj = EnumEmployee.hireType.find(item => Number(item.id) === Number(value))
          userArr.push(obj ? obj.value : '')
        } else if (enkey === 'timeOfEntry') {
          userArr.push(formatDate(value))
        } else {
          userArr.push(value)
        }
      }
      // console.log(userArr)
      return userArr
    },
    // 打开新增弹窗
    dialogShow() {
      this.showDialog = true
    },
    // 显示二维码
    showCode(url) {
      if (url) {
        this.isShowCode = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCanvas, url, {
          // 给二维码加样式
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 打开分配角色弹窗
    showRoleDialogFn(id) {
      this.userId = id
      this.$refs.roleDialog.getCheckList(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
